<template>
  <div class="m-updatePwd">
    <el-form class="form" ref='form' label-width="120px" :model="form" :rules='rules'>
      <el-form-item label="原密码：" prop='oldPwd'>
        <el-input type="password" placeholder="请输入原密码" v-model="form.oldPwd"></el-input>
      </el-form-item>
      <el-form-item label="新密码：" prop='newPwd'>
        <el-input type="password" placeholder="请输入6位以上数字与字母组合" v-model="form.newPwd"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码：" prop='checkNewPwd'>
        <el-input type="password" placeholder="请重新输入新密码" v-model="form.checkNewPwd"></el-input>
      </el-form-item>
      <el-form-item align='right'>
        <el-button type="primary" @click="reset">重置</el-button>
        <el-button type="primary" @click="confirm">确认修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import elementMixin from '@/mixins/elementPublicMixin'

export default {

  name: 'updatePwd',

  mixins: [elementMixin],

  data() {
    return {
      form: {
        oldPwd: '',
        newPwd: '',
        checkNewPwd: ''
      },
      rules: {
        oldPwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, message: '长度至少 6 个字符', trigger: 'blur' }
        ],
        newPwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '长度至少 6 个字符', trigger: 'blur' }
        ],
        checkNewPwd: [
          { required: true, message: '请输入确认新密码', trigger: 'blur' },
          { min: 6, message: '长度至少 6 个字符', trigger: 'blur' }
        ]
      },
      ifRequesting: false
    }
  },

  methods: {
    confirm() {
      if (this.ifRequesting) return
      this.$refs.form.validate((valid) => {
        if (!valid) return
        if (this.form.newPwd !== this.form.checkNewPwd) {
          this.__notify('警告', '新密码与确认密码不相同', 'warning')
          return
        }
        this.updatePwd()
      })
    },

    async updatePwd() {
      this.ifRequesting = true
      const form = this.form
      const { code } = await this.$api.adminUpdatePwd({ oldPassword: +form.oldPwd, newPassword: +form.newPwd, rePassword: +form.checkNewPwd })
      this.ifRequesting = false
      if (code === 200) {
        this.__notify('修改密码成功')
        this.$router.push({ name: 'task' })
      }
    },

    reset() {
      this.$refs.form.resetFields()
    }
  }

}
</script>

<style lang="less">
.m-updatePwd {
  .form {
    max-width: 672px;
  }
}
</style>
